from decimal import Decimal
from apps.user.dao import UserDao
from apps.pay.recordIncomes.dao import RecordIncomesDao

# 计算平级奖励
def countLevelAward(_parent, award, order, rank, key):
    print('计算平级奖励', _parent, award, order, rank)
    _levelAwards = rank.rank_levelAward.all().order_by('-awardRate')
    for levelAward in _levelAwards:
        print('levelAward', levelAward.grade)
        if _parent.parent:
            _parent = findLastRankByUserAndGrade(_parent.parent, levelAward.grade, key)
            if _parent:
                print('增加平级收益', _parent.id, award * levelAward.awardRate)
                award = award * levelAward.awardRate
                addAward('levelAward', _parent, award, order)
            else:
                break
        
# 查找最近级别的用户
def findLastRankByUserAndGrade(parent, grade, key):
    print('要查找的用户', parent)
    if parent.id:
        if UserDao().findRankOfUser(parent, key).grade == grade:
            print('找到用户', parent)
            return parent
        else:
            print('不是级别为2的用户', parent)
            if parent.parent:
                return findLastRankByUserAndGrade(parent.parent, grade)
            return None
    else:
        print('一个级别为2的用户也没有')
        return None

# 增加见点奖
def addAward(awardType, _parent, award, order):
    print('发放平级奖', award)
    UserDao().addWallet('incomes', _parent, award)
    UserDao().addWallet('historyIncomes', _parent, award)
    # 新增钱包记录
    data = {}
    data['lessee'] = order.lessee.id
    data['scene'] = awardType#'gradeAward'
    data['user'] = _parent.id
    data['fromUser'] = order.user.id
    data['orderId'] = order.orderId
    data['money'] = Decimal(award).quantize(Decimal("0.00"))
    data['payway'] = 'incomes'
    data['changeWay'] = 'add'
    RecordIncomesDao().create(data)